<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="85px"
    >
      <el-form-item label="方案名称" prop="name">
        <ns-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入方案名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" v-hasPermi="['amp:strategy-testing:search']" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" v-hasPermi="['amp:strategy-testing:search']" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <ContentWrap>
    <div class="handle-btns">
      <el-button type="primary" @click="handleUpdate()" v-hasPermi="['amp:strategy-testing:add']"
        >新增</el-button
      >
      <el-button type="primary" @click="createReport">生成报告</el-button>
    </div>
    <el-table v-loading="loading" :data="list" row-key="id" show-overflow-tooltip ref="listRef">
      <el-table-column type="selection" width="80" />
      <el-table-column type="index" width="80" label="序号" align="center" />
      <el-table-column prop="name" label="测试方案" align="center" />
      <el-table-column prop="strategyName" label="测试策略" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center" />
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.status" :type="statusMap.get(scope.row.status)?.type">{{
            statusMap.get(scope.row.status)?.label || ''
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="错误信息" align="center">
        <template #default="scope">
          <el-button
            v-if="scope.row.status == 2"
            link
            type="primary"
            @click="openError(scope.row.errors)"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            @click="handleOperate(row, 0)"
            v-if="[2, 3, 4, 6].includes(row.status)"
            v-hasPermi="['amp:strategy-testing:opration']"
          >
            开始
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleOperate(row, 1)"
            v-if="row.status == 1"
            v-hasPermi="['amp:strategy-testing:opration']"
          >
            暂停
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleOperate(row, 2)"
            v-if="row.status == 1"
            v-hasPermi="['amp:strategy-testing:opration']"
          >
            停止
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleOperate(row, 3)"
            v-if="row.status == 5"
            v-hasPermi="['amp:strategy-testing:opration']"
          >
            继续
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleUpdate(row, 1)"
            :disabled="row.status == 1"
            v-hasPermi="['amp:strategy-testing:update']"
          >
            编辑方案
          </el-button>
          <el-button
            link
            type="primary"
            @click="showReport(row)"
            :disabled="row.status != 3"
            v-hasPermi="['amp:strategy-testing:report']"
          >
            测试报告
          </el-button>
          <el-button
            link
            type="danger"
            @click="delList(row.id)"
            :disabled="row.status == 1"
            v-hasPermi="['amp:strategy-testing:delete']"
            >删除
          </el-button></template
        >
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.page"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
  <test-edit
    ref="editRef"
    v-model:visible="dialogVisible"
    :dialog-title="dialogTitle"
    :id="detailId"
    @success="getList"
  />
  <TestReport v-model:visible="reportVisible" :id="detailId" />
  <TaskError ref="taskErrorRef" />

  <Dialog title="报告" width="1000px" v-model="reportVis" v-if="reportVis">
    <el-table :data="reportList" row-key="id" show-overflow-tooltip height="400px">
      <el-table-column type="index" width="80" label="序号" align="center" />
      <el-table-column prop="name" label="测试方案名称" align="center" />
      <el-table-column prop="hit" label="正向命中率" align="center">
        <template #default="scope">
          {{ (scope.row.hit * 100).toFixed(2) + '%' }}
        </template>
      </el-table-column>
      <el-table-column prop="miss" label="反向命中率" align="center">
        <template #default="scope">
          {{ (scope.row.miss * 100).toFixed(2) + '%' }}
        </template>
      </el-table-column>
      <el-table-column prop="score" label="得分" align="center">
        <template #default="scope">
          {{ (scope.row.score * 100).toFixed(2) }}
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex; align-items: baseline">
      <h3 style="white-space: nowrap">结论：</h3>
      <div
        >{{ bestData.name }}为本次测试范围的最佳策略，在{{ bestData.hitDown }}个正向文件中命中{{
          bestData.hitUp
        }}个，命中率为{{ (bestData.hit * 100).toFixed(2) }}%，在{{
          bestData.missDown
        }}个反向文件中命中{{ bestData.missUp }}个，命中率为{{
          (bestData.miss * 100).toFixed(2)
        }}%,得分{{ (bestData.score * 100).toFixed(2) }}</div
      >
    </div>
    <template #footer>
      <el-button @click="reportVis = false">关 闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import {
  pageStrategyTesting,
  delStrategyTesting,
  operateStatus,
  getReport
} from '@/api/develop/strategyTesting'
import TestEdit from './component/TestEdit.vue'
import TestReport from './component/TestReport.vue'
import { statusMap } from '@/views/develop/constants'
import TaskError from '@/views/develop/clustering/dialog/TaskError.vue'
const statusInfo = ['', '进行中', '错误', '已完成']
const taskErrorRef = ref<InstanceType<typeof TaskError>>()
const queryFormRef = ref() // 搜索的表单
const total = ref(10) // 列表的总页数
const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: ''
})
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

const statusName = ['start', 'pause', 'stop', 'resume']
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const { count, data } = await pageStrategyTesting(toRaw(queryParams))
    list.value = data
    total.value = count
  } finally {
    loading.value = false
  }
}
getList()

const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const detailId = ref()
const editRef = ref()
/** 添加/修改操作 */
const handleUpdate = (val?, type?) => {
  dialogTitle.value = type ? (type === 1 ? '修改' : '详情') : '新增'
  detailId.value = val?.id
  editRef.value.setFormData(val)
  dialogVisible.value = true
}
const { proxy } = getCurrentInstance()
const message = useMessage() // 消息弹窗
// 删除
const delList = (id) => {
  proxy?.$modal
    .confirm(`确定要删除吗？`)
    .then(() => {
      delStrategyTesting({ id }).then(() => {
        getList()
        message.success('删除成功')
      })
    })
    .catch(() => {})
}

const reportVisible = ref(false)
const showReport = (val) => {
  reportVisible.value = true
  detailId.value = val.id
}

function openError(error) {
  taskErrorRef.value?.open(error)
}

async function handleOperate(row, status) {
  await operateStatus({ taskId: row.id, operation: statusName[status] })
  getList()
}

// 生成报告
const reportVis = ref(false)
const reportList = ref([])
const listRef = ref()
const bestData = ref({})
async function createReport() {
  const selectData = listRef.value.getSelectionRows()
  if (selectData.length === 0) {
    return ElMessage.warning('请选择数据')
  }
  const data = await getReport(selectData.map((item) => item.id))
  reportList.value = data
  bestData.value = data[0]
  let max = bestData.score
  data.forEach((item) => {
    if (item.score > max) {
      max = item.score
      bestData.value = item
    }
  })
  reportVis.value = true
}
</script>

<style lang="scss" scoped>
.handle-btns {
  margin-bottom: 20px;
}
</style>
